package com.googlecode.gamedroid.event.source;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

import com.googlecode.gamedroid.event.Event;
import com.googlecode.gamedroid.event.EventKey;
import com.googlecode.gamedroid.event.EventReceiver;
import com.googlecode.gamedroid.event.EventType;

public class GameButton extends Button implements EventSource
{
	private Event mEvent = new Event(EventType.KEY, EventKey.BTN_0);
	private boolean mPressed = false;
	private EventReceiver mReceiver = null;
	protected int[] mSize = new int[4];
	
	public GameButton(Context context)
	{
		super(context);
	}
	
	public GameButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}
	
	public GameButton(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}
	
	@Override
	protected void dispatchSetPressed(boolean pressed)
	{
		super.dispatchSetPressed(pressed);
		
		if(pressed == mPressed)
			return;
		
		mPressed = pressed;
		
		if(mReceiver == null)
			return;
		
		mEvent.setValue((short) (pressed ? 1 : 0));
		mReceiver.emit(mEvent, true);
		mReceiver.feedback();
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		super.onSizeChanged(w, h, oldw, oldh);
		
		int[] location = new int[2];
		
		getLocationInWindow(location);
		
		mSize[0] = location[0];
		mSize[1] = location[1];
		mSize[2] = location[0] + w;
		mSize[3] = location[1] + h;
	}
	
	@Override
	public Event[] getEventDefinitions()
	{
		Event[] events = new Event[1];
		events[0] = mEvent;
		return events;
	}
	
	public int[] getSize()
	{
		return mSize;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		return false;
	}
	
	@Override
	public void reset()
	{
		setPressed(false);
	}
	
	@Override
	public void setEvents(short[] events)
	{
		if(events.length != 1)
			throw new IllegalArgumentException();
		
		mEvent.setKey(events[0]);
	}
	
	@Override
	public void setReceiver(EventReceiver receiver)
	{
		mReceiver = receiver;
	}
}
